// Authors: Marsbighead <duanhmhy@126.com>
//
// # Copyright (c) 2024 Marsbighead
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

package pgcluster

import (
	"fmt"
	"phant-operator/pkg/apis/phant/v1alpha1"
	"phant-operator/pkg/controller"

	mm "phant-operator/pkg/manager/member"
	"phant-operator/pkg/metrics"
	"time"

	apps "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
	"k8s.io/klog/v2"
)

var (
	partoniTackerKey = "patroni/tracker"
)

// Controller controls postgresclusters.
type Controller struct {
	deps *controller.Dependencies
	// control returns an interface capable of syncing a postgres cluster.
	// Abstracted out for testing.
	control ControlInterface
	// postgresclusters that need to be synced.
	queue workqueue.RateLimitingInterface
	// tacker to remove endpoints created by Patroni
	// to-do: maybe reconstruct
	tracker mm.PatroniTracker
}

// NewController creates a postgrescluster controller.
func NewController(deps *controller.Dependencies) *Controller {
	//suspender := suspender.NewSuspender(deps)
	//podVolumeModifier := volumes.NewPodVolumeModifier(deps)

	c := &Controller{
		deps: deps,
		queue: workqueue.NewNamedRateLimitingQueue(
			controller.NewControllerRateLimiter(1*time.Second, 100*time.Second),
			"postgrescluster",
		),
		control: NewDefaultPostgresClusterControl(
			mm.NewPatroniManager(deps),
			mm.NewPatroniMemberManager(deps),
			mm.NewPostgresMemberManager(deps),
			deps.Recorder),
		tracker: mm.NewPatroniTracker(deps),
	}

	pgClusterInformer := deps.InformerFactory.Phant().V1alpha1().PostgresClusters()
	statefulsetInformer := deps.KubeInformerFactory.Apps().V1().StatefulSets()
	pgClusterInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: c.enqueuePostgresCluster,
		UpdateFunc: func(old, cur interface{}) {
			c.enqueuePostgresCluster(cur)
		},
		DeleteFunc: c.enqueuePostgresCluster,
	})
	statefulsetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: c.addStatefulSet,
		UpdateFunc: func(old, cur interface{}) {
			c.updateStatefulSet(old, cur)
		},
		DeleteFunc: c.deleteStatefulSet,
	})
	return c
}

// Name returns the name of the postgrescluster controller
func (c *Controller) Name() string {
	return "postgrescluster"
}

// Run runs the postgrescluster controller.
func (c *Controller) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

	klog.Info("Starting postgrescluster controller")
	defer klog.Info("Shutting down postgrescluster controller")

	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	<-stopCh
}

// worker runs a worker goroutine that invokes processNextWorkItem until the the controller's queue is closed
func (c *Controller) worker() {
	for c.processNextWorkItem() {
	}
}

// processNextWorkItem dequeues items, processes them, and marks them done. It enforces that the syncHandler is never
// invoked concurrently with the same key.
func (c *Controller) processNextWorkItem() bool {
	metrics.ActiveWorkers.WithLabelValues(c.Name()).Add(1)
	defer metrics.ActiveWorkers.WithLabelValues(c.Name()).Add(-1)
	key, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(key)
	// manage tracker process
	if key.(string) == partoniTackerKey {
		if err := c.tracker.StartTrackPatroniEndPoints(); err != nil {
			utilruntime.HandleError(fmt.Errorf("Failed to update endpoints created by patroni, err: %v", err))
		}
		if c.tracker.Length() > 0 {
			c.queue.AddRateLimited(key)
		} else {
			c.queue.Forget(key)
		}
		klog.Infof("Capture posgresclusters key=%s", key)
		return true
	}

	if err := c.sync(key.(string)); err != nil {

		utilruntime.HandleError(fmt.Errorf("PostgresCluster: %v, sync failed %v, requeuing", key.(string), err))

		c.queue.AddRateLimited(key)
	} else {
		c.queue.Forget(key)
	}
	return true
}

// sync syncs the given tidbcluster.
func (c *Controller) sync(key string) error {
	startTime := time.Now()
	defer func() {
		duration := time.Since(startTime)
		//metrics.ReconcileTime.WithLabelValues(c.Name()).Observe(duration.Seconds())
		klog.V(4).Infof("Finished syncing Postgres Cluster %q (%v)", key, duration)
	}()

	ns, name, err := cache.SplitMetaNamespaceKey(key)
	if err != nil {
		return err
	}
	pg, err := c.deps.PostgresClusterLister.PostgresClusters(ns).Get(name)
	if errors.IsNotFound(err) {
		c.tracker.StartTrackPostgresCluster(ns, name)
		c.queue.Add(partoniTackerKey)
		klog.Infof("Postgres has been deleted %v, start to track endpoints owned by the PostgresCluster", key)
		return nil
	}
	if err != nil {
		return err
	}

	return c.syncPostgresCluster(pg.DeepCopy())
}

func (c *Controller) syncPostgresCluster(pg *v1alpha1.PostgresCluster) error {
	return c.control.UpdatePostgresCluster(pg)
}

// addStatefulSet adds the postgrescluster for the statefulset to the sync queue
func (c *Controller) addStatefulSet(obj interface{}) {
	set := obj.(*apps.StatefulSet)
	ns := set.GetNamespace()
	setName := set.GetName()

	if set.DeletionTimestamp != nil {
		// on a restart of the controller manager, it's possible a new statefulset shows up in a state that
		// is already pending deletion. Prevent the statefulset from being a creation observation.
		c.deleteStatefulSet(set)
		return
	}

	// If it has a ControllerRef, that's all that matters.
	pg := c.resolvePostgresClusterFromSet(ns, set)
	if pg == nil {
		return
	}
	klog.V(4).Infof("StatefulSet %s/%s created, postgresCluster: %s/%s", ns, setName, ns, pg.Name)
	c.enqueuePostgresCluster(pg)
}

// updateStatefulSet adds the postgrescluster for the current and old statefulsets to the sync queue.
func (c *Controller) updateStatefulSet(old, cur interface{}) {
	curSet := cur.(*apps.StatefulSet)
	oldSet := old.(*apps.StatefulSet)
	ns := curSet.GetNamespace()
	setName := curSet.GetName()
	if curSet.ResourceVersion == oldSet.ResourceVersion {
		// Periodic resync will send update events for all known statefulsets.
		// Two different versions of the same statefulset will always have different RVs.
		return
	}

	// If it has a ControllerRef, that's all that matters.
	pg := c.resolvePostgresClusterFromSet(ns, curSet)
	if pg == nil {
		return
	}
	klog.V(4).Infof("StatefulSet %s/%s updated, postgresCluster: %s/%s", ns, setName, ns, pg.Name)
	c.enqueuePostgresCluster(pg)
}

// deleteStatefulSet enqueues the postgrescluster for the statefulset accounting for deletion tombstones.
func (c *Controller) deleteStatefulSet(obj interface{}) {
	set, ok := obj.(*apps.StatefulSet)

	// When a delete is dropped, the relist will notice a statefuset in the store not
	// in the list, leading to the insertion of a tombstone object which contains
	// the deleted key/value.
	if !ok {
		tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
		if !ok {
			utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %+v", obj))
			return
		}
		set, ok = tombstone.Obj.(*apps.StatefulSet)
		if !ok {
			utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a statefuset %+v", obj))
			return
		}
	}

	ns := set.GetNamespace()
	setName := set.GetName()

	// If it has a PostgresCluster, that's all that matters.
	pg := c.resolvePostgresClusterFromSet(ns, set)
	if pg == nil {
		return
	}
	klog.V(4).Infof("StatefulSet %s/%s deleted through %v.", ns, setName, utilruntime.GetCaller())
	c.enqueuePostgresCluster(pg)
}

// enqueuepostgresCluster enqueues the given postgrescluster in the work queue.
func (c *Controller) enqueuePostgresCluster(obj interface{}) {
	key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
	if err != nil {
		if errors.IsNotFound(err) {
			//c.control.UpdatePostgresCluster()

			klog.Infof("PostgresCluster object %+v has been deleted.", obj)
		}
		utilruntime.HandleError(fmt.Errorf("Couldn't get key for object %+v: %v", obj, err))
		return
	}
	c.queue.Add(key)
}

// resolvepostgresClusterFromSet returns the postgresCluster by a StatefulSet,
// or nil if the StatefulSet could not be resolved to a matching postgresCluster
// of the correct Kind.
func (c *Controller) resolvePostgresClusterFromSet(namespace string, set *apps.StatefulSet) *v1alpha1.PostgresCluster {
	controllerRef := metav1.GetControllerOf(set)
	if controllerRef == nil {
		return nil
	}

	// We can't look up by UID, so look up by Name and then verify UID.
	// Don't even try to look up by Name if it's the wrong Kind.
	if controllerRef.Kind != controller.ControllerKind.Kind {
		return nil
	}
	pg, err := c.deps.PostgresClusterLister.PostgresClusters(namespace).Get(controllerRef.Name)
	if err != nil {
		return nil
	}
	if pg.UID != controllerRef.UID {
		// The controller we found with this Name is not the same one that the
		// ControllerRef points to.
		return nil
	}
	return pg
}
